/**
* vchat operate
* Author: Feil.Wang
* Date: 2013.11.28
*/

/*function initChatAreaHeight(){
    var img = $("#bannerImg");
    var imgHeight = img.height();
    $("#chatListWrap").height(638-imgHeight);
}

window.onload = initChatAreaHeight; */      //图片高度必须要用window.onload方法才能正确获取

;(function(window,undefined){
	var vchat = {
		setting : {
			topVideo : "",		    //上部分视频（用户）
			bottomVideo : "",		//下部分视频（管理员）
            curVideoNum : 0,        //当前视频个数
			isComplate : false	    //动画是否完成
		},
		init : function(){
			this.setting.topVideo = $("#vchatDispTop");
			this.setting.bottomVideo = $("#vchatDispBottom");

			this.setting.isComplate = true;
			this.scroll("#participantList");
            this.scroll("#chatListWrap","bottom");
            this.chatAreaSize();
			this.msgFn();
			this.textStyle();

            //预告滚动
            var scrollTime=setInterval('vchat.autoScroll(".forecast-scroll")',3000)
            $(".forecast-scroll").hover(function(){
                clearInterval(scrollTime);
            },function(){
                scrollTime=setInterval('vchat.autoScroll(".forecast-scroll")',3000);
            });

		},
        //检查视频是否已经加入或退出的状态
        checkStatus : function(o){
            var val = o.css("opacity");
            return val;
        },



		//用户视频加入视频
		userJoin : function(){
            var that = this;
            if(that.setting.curVideoNum == 0 && that.setting.isComplate){
                if(that.checkStatus(that.setting.topVideo)==1)return;
                that.setting.isComplate = false;
                $("#participantList").animate({
                    "height" : "451px"
                },500,function(){
                    that.setting.topVideo.css({"top" : "205px"}).animate({"opacity" : "1"},500);
                    that.scroll("#participantList");
                    that.setting.curVideoNum = 1;
                    that.setting.isComplate = true;
                });
            }else if(that.setting.curVideoNum == 1 && that.setting.isComplate){
                if(that.checkStatus(that.setting.topVideo)==1)return;
                that.setting.isComplate = false;
                $("#participantList").animate({
                    "height" : "250px"
                },500,function(){
                    that.setting.topVideo.css({"top" : "0px"}).animate({"opacity" : "1"},500);
                    that.scroll("#participantList");
                    that.setting.curVideoNum = 2;
                    that.setting.isComplate = true;
                });
            }

		},
		//管理员视频加入视频
		adminJoin : function(){
            var that = this;
            if(that.setting.curVideoNum == 0 && that.setting.isComplate){
                if(that.checkStatus(that.setting.bottomVideo)==1)return;
                that.setting.isComplate = false;
                $("#participantList").animate({"height" : "451px"},500,function(){
                    that.setting.bottomVideo.css({ "top" : "205px"}).animate({"opacity" : "1" },500);
                    that.scroll("#participantList");
                    that.setting.curVideoNum = 1;
                    that.setting.isComplate = true;
                });
            }else if(that.setting.curVideoNum == 1 && that.setting.isComplate){
                if(that.checkStatus(that.setting.bottomVideo)==1)return;
                that.setting.isComplate = false;
                $("#participantList").animate({"height" : "250px"},500);
                that.setting.topVideo.animate({"top":"0px"},500,function(){
                    that.setting.bottomVideo.css({"top" : "205px"}).animate({"opacity" : "1"},500);
                    that.scroll("#participantList");
                    that.setting.curVideoNum = 2;
                    that.setting.isComplate = true;
                });
            }

		},
		//用户视频退出
		userExit : function(){
            var that = this;
            if(that.setting.curVideoNum == 1 && that.setting.isComplate){
                if(that.checkStatus(that.setting.topVideo)==0)return;
                that.setting.isComplate = false;
                that.setting.topVideo.animate({"opacity":"0"},500,function(){
                    $("#participantList").animate({"height" : "656px"},500,function(){
                        that.scroll("#participantList");
                        that.setting.curVideoNum = 0;
                        that.setting.isComplate = true;
                    });
                });
            }else if(that.setting.curVideoNum == 2 && that.setting.isComplate){
                if(that.checkStatus(that.setting.topVideo)==0)return;
                that.setting.isComplate = false;
                that.setting.topVideo.animate({"opacity":"0"},500,function(){
                    $("#participantList").animate({"height" : "451px"},500,function(){
                        that.scroll("#participantList");
                        that.setting.curVideoNum = 1;
                        that.setting.isComplate = true;
                    });
                });

            }
		},
		//管理员视频退出
		adminExit : function(){
            var that = this;
            if(that.setting.curVideoNum == 1 && that.setting.isComplate){
                if(that.checkStatus(that.setting.bottomVideo)==0)return;
                that.setting.isComplate = false;
                that.setting.bottomVideo.animate({"opacity":"0"},500,function(){
                    $("#participantList").animate({"height" : "656px"},500,function(){
                        that.scroll("#participantList");
                        that.setting.curVideoNum = 0;
                        that.setting.isComplate = true;
                    });
                });
            }else if(that.setting.curVideoNum == 2 && that.setting.isComplate){
                if(that.checkStatus(that.setting.bottomVideo)==0)return;
                that.setting.isComplate = false;
                that.setting.bottomVideo.animate({"opacity":"0"},500,function(){
                    that.setting.topVideo.animate({"top":"205px"},500);
                    $("#participantList").animate({"height" : "451px"},500,function(){
                        that.scroll("#participantList");
                        that.setting.curVideoNum = 1;
                        that.setting.isComplate = true;
                    });
                });

            }
		},

		scroll : function(obj,pos){
			var pane = $(obj);
			pane.jScrollPane({
				mouseWheelSpeed: 30,
                verticalDragMinHeight:20
			});
			var api = pane.data("jsp");
			if(pos == "top"){
				api.scrollToY(0);
			}else if(pos == "bottom"){
				var scrollAreaHeight = pane.find(".jspPane").height();		
				api.scrollToY(scrollAreaHeight);
			}
		},

        //预告向上自动滚动
        autoScroll : function(obj){
            $(obj).find("ul:first").animate({
                marginTop:"-25px"
            },800,function(){
                $(this).css({marginTop:"0px"}).find("li:first").appendTo(this);
            });
        },

        chatAreaSize : function(){
            var that = this;
            var btn = $("#chatAreaSizeBtn");
            var topImgHeight = $("#bannerImg").height();
            var chatAreaHeight = 638-topImgHeight;
            $("#chatListWrap").height(chatAreaHeight);
            btn.click(function(){
                if($("#tchatArea").hasClass("unfold")){
                    $("#chatListWrap").animate({"height":chatAreaHeight},500,function(){
                        that.scroll("#chatListWrap");
                        btn.removeClass("arrow-switch-down").attr("title","收起图片");
                        $("#tchatArea").removeClass("unfold");
                    });
                }else{
                    $("#chatListWrap").animate({"height":"548px"},500,function(){
                        that.scroll("#chatListWrap");
                        btn.addClass("arrow-switch-down").attr("title","展开图片");
                        $("#tchatArea").addClass("unfold");

                    });
                }
            });
        },
		msgFn : function(){
			var $textInput = $("#textInput")
                ,$clearTextBtn = $("#clearTextBtn")
                ,$submitMsgBtn = $("#submitMsgBtn")
                ,$selectUser = $("#selectChatUser")
                ,$userListWrap = $("#userListWrap")
                ,$userList = $("#userList");
			
			//输入框操作	
			$textInput.focus(function(){
				$(this).addClass("text-input-focus");
				$clearTextBtn.show();
			});
			$(document.body).click(function(e){
				var target = $(e.target);
				if(target.closest("#textInput").length == 0){
					$textInput.blur();
					$textInput.removeClass("text-input-focus");
					$clearTextBtn.hide();
				}
			});
			$clearTextBtn.click(function(e){	//清除文字
				e.stopPropagation();
				$textInput.val("");
				$textInput.focus();
			});
			
			//选择聊天对象
			$selectUser.click(function(e){
				e.stopPropagation();
				var liLength = $userListWrap.find("li").length;
				if(liLength>10){
					$userList.height(240);
				}	
				if($userListWrap.css("display") == "none"){
					$userListWrap.slideDown(300,function(){
						if(liLength>10){
							vchat.scroll("#userList");
						}
					});
				}else{
					return;
				}
			});
			
			$userList.find("li").click(function(){
				var uname = $(this).text();
				$("#selectedUser").text(uname).attr("title",uname);
				$userListWrap.slideUp(300);
			});
			
			$(document.body).click(function(e){
				var target  = $(e.target);
				if(target.closest("#userListWrap").length == 0){
					$userListWrap.slideUp(300);
				}
				
			});
			
			//发送消息
			$submitMsgBtn.click(function(){
				var msg = $textInput.val();
				var uName = $("#selectedUser").text();
				var oddClass = $("#chatMsgList").find("li:last").hasClass("odd")?"":"odd";
				var textStyle = $("#textInput").attr("style")
				if(!msg==""){
					$("#chatMsgList").append('<li class="'+oddClass+' role-myself">'
											+'	<div class="u-avatar">'
											+'		<img src="../static/images/u-avatar.png" />'
											+'		<a class="e-vcard" href="javascript:;"></a>'
											+'	</div>'
											+'	<dl>'
											+'		<dt>我对<span class="other-name">'+ uName +'</span>说</dt>'
											+'		<dd style="'+ textStyle +'">'+ msg +'</dd>'
											+'	</dl>'
											+'</li>')
					vchat.scroll("#chatListWrap","bottom");
                    $textInput.val("");
				}else{
					setFocus();
				}
			});
			//内容为空时闪红提示
			function setFocus(c){
				if(typeof(c)=='undefined'){
					var c = 0;
				}
				if(c%2==0){
					$textInput.addClass("redFlash");
				}else{
					$textInput.removeClass("redFlash");
				}
				if(c<3){
					setTimeout(function(){setFocus(++c)},150);
				}
			}
			
			//交换名片
			$("#chatMsgList li").find(".u-avatar").live("mouseenter",function(){
				$(this).find(".e-vcard").show();
			});
			$("#chatMsgList li").find(".u-avatar").live("mouseleave",function(){
				$(this).find(".e-vcard").hide();
			});
			
		},
		textStyle : function(){
			var $selectColor = $("#selectColor"),
				$colorArea = $("#colorArea"),
				$underlinePost = $("#underlinePost"),
				$boldPost = $("#boldPost"),
				$italicPost = $("#italicPost"),
				$textInput = $("#textInput");
				
			if($.cookie('textStyle')!==null){
				$textInput.attr("style",$.cookie('textStyle'));
				
				if($textInput.css("text-decoration")=="underline"){
					$underlinePost.attr("checked",true);
				}else{
					$underlinePost.attr("checked",false);
				}
				if($textInput.css("font-weight")=="bold" || $textInput.css("font-weight")=="700"){
					$boldPost.attr("checked",true);
				}else{
					$boldPost.attr("checked",false);
				}
				if($textInput.css("font-style")=="italic"){
					$italicPost.attr("checked",true);
				}else{
					$italicPost.attr("checked",false);
				}
				$selectColor.css("background-color",$textInput.css("color"));
			}
			
			$underlinePost.click(function(){
				if(this.checked){
					$textInput.css("text-decoration","underline");
					setCookie();
				}else{
					$textInput.css("text-decoration","none");
					setCookie();
				}
			});
			
			$boldPost.click(function(){
				if(this.checked){
					$textInput.css("font-weight","bold");
					setCookie();
				}else{
					$textInput.css("font-weight","normal");
					setCookie();
				}
			});
			
			$italicPost.click(function(){
				if(this.checked){
					$textInput.css("font-style","italic");
					setCookie();
				}else{
					$textInput.css("font-style","normal");
					setCookie();
				}
			});

			$(".text-color-wrap").click(function(){
				$colorArea.show();
			});
			
			$colorArea.find("a").click(function(e){
				var curColor = $(this).attr("data-color");
				$selectColor.css("background-color",curColor);
				$textInput.css("color",curColor);
				setCookie();
				$colorArea.hide();
				e.stopPropagation();
			});
			$(document.body).click(function(e){
				var target  = $(e.target);
				if(target.closest(".text-color-wrap").length == 0){
					$colorArea.hide();
				}
			});
			function setCookie(){
				var styleVal = $textInput.attr("style");
				$.cookie('textStyle', styleVal, { expires: 30, path: '/' });  
			}
			
		}
	}
    window.vchat = vchat;
})(window);

/**
 * Cookie plugin
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(function(){
	vchat.init();

	$("#userJoin").click(function(){
		vchat.userJoin();
	});	
	$("#adminJoin").click(function(){
		vchat.adminJoin();
	});
	$("#userExit").click(function(){
		vchat.userExit();
	});
	$("#adminExit").click(function(){
		vchat.adminExit();
	});

});

